<!-- 点击编辑弹出的dialog -->
<template>
     <el-dialog
            :title="detailRow.name"
            :visible.sync="visible"
            :modal-append-to-body='false'
            :close-on-click-modal='false'
            @close="close"
           >
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户aid" prop="aid" v-show="false">
                    <el-input type="hidden" v-model="ruleForm.aid" v-show="false"></el-input>
                </el-form-item>
                <el-form-item label="上传头像" prop="avatar">
                    <el-upload
                        class="avatar-uploader"
                        action=""
                        :show-file-list="false"
                        :http-request="uploadImage"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" title="点击更换头像">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input prefix-icon="el-icon-s-custom" v-model="ruleForm.name" placeholder="请输入姓名" clearable></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender" >
                   <el-radio-group v-model="ruleForm.gender">
                        <el-radio label="男"></el-radio>
                        <el-radio label="女"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="账号" prop="account">
                    <el-input prefix-icon="el-icon-user" v-model="ruleForm.account" placeholder="请输入账号" clearable></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input prefix-icon="el-icon-phone" v-model="ruleForm.phone" placeholder="请输入账号" clearable></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input prefix-icon="el-icon-message" v-model="ruleForm.email" placeholder="请输入邮箱" clearable></el-input>
                </el-form-item>
                <el-form-item label="联系地址" prop="address">
                    <el-input prefix-icon="el-icon-map-location" v-model="ruleForm.address" placeholder="请输入地址" clearable></el-input>
                </el-form-item>
                <el-form-item label="学校" prop="school">
                    <el-input prefix-icon="el-icon-map-location" v-model="ruleForm.school" placeholder="请输入学校" clearable></el-input>
                </el-form-item>
                <el-form-item label="婚姻状况" prop="marital_status">
                    <el-radio-group v-model="ruleForm.marital_status">
                        <el-radio label="已婚"></el-radio>
                        <el-radio label="未婚"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否管理员" prop="isAdmin">
                    <el-switch v-model="ruleForm.isAdmin"></el-switch>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                    <el-button @click="resetForm('ruleForm')">重置</el-button>
                </el-form-item>
            </el-form>
    </el-dialog>
</template>

<script>
import { addUser, editUser, checkAccountExist, checkPhoneExist } from '../../api/userManage'
import { client } from '../../utils/alioss';
export default {
    data () {
        var checkPhone = (rule, value, callback) => {
            const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
            if (!value) {
                return callback(new Error('电话号码不能为空'))
            }
            setTimeout(() => {
            // Number.isInteger是es6验证数字是否为整数的方法,但是我实际用的时候输入的数字总是识别成字符串
            // 所以我就在前面加了一个+实现隐式转换

            if (!Number.isInteger(+value)) {
                callback(new Error('请输入数字值'))
            } else {
                if (phoneReg.test(value)) {

                    // 判断用户账号是否存在相同
                    const params = {
                        aid: this.ruleForm.aid ? this.ruleForm.aid : -1,
                        phone: this.ruleForm.phone,
                    }
                    checkPhoneExist(params).then(res=>{
                        if(res.data.data.isExisted === true){
                            callback(new Error('该手机号已存在，请重新输入！'));
                        }else{
                            callback();
                        }
                    });
                } else {
                callback(new Error('电话号码格式不正确'))
                }
            }
            }, 100)
        }
        var checkEmail = (rule, value, callback) => {
            const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
            if (!value) {
            return callback(new Error('邮箱不能为空'))
            }
            setTimeout(() => {
                if (mailReg.test(value)) {
                    callback()
                } else {
                    callback(new Error('请输入正确的邮箱格式'))
                }   
            }, 100)
        }
        var checkAccount = (rule, value, callback) => {
            if (!value) {
            return callback(new Error('账号不能为空'))
            }
            // 判断用户账号是否存在相同
            const params = {
                aid: this.ruleForm.aid ? this.ruleForm.aid : -1,
                account: this.ruleForm.account,
            }
            checkAccountExist(params).then(res=>{
                if(res.data.data.isExisted === true){
                    callback(new Error('该账号已存在，请重新输入！'));
                }else{
                    callback();
                }
            });
        }
    
        return {
            visible: this.show,
            imageUrl: '',
            ruleForm: {
                aid: '',
                name: '',
                gender: '',
                account: '',
                phone: '',
                email: '',
                address: '',
                marital_status: '',
                isAdmin: false,
                school: '',
            },
            rules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' }
                ],
                school: [
                    { required: true, message: '请输入学校', trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '请选择性别', trigger: 'change' }
                ],
                account: [
                    { validator: checkAccount, trigger: ['blur','change'] }    
                ],
                phone: [
                    { validator: checkPhone, trigger: ['blur','change'] }
                ],
                email: [
                    { validator: checkEmail, trigger: ['blur','change'] }
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' }
                ],
                marital_status: [
                    { required: true, message: '请选择婚姻状态', trigger: 'change' }
                ],
            }
        };
    },
    props: {
        show: {
            type: Boolean,
            default: false
        },
        detailRow: {
            type: Object,
            require: true,
        }
    },
    watch: {
        show () {
            this.visible = this.show;
        },
        detailRow() {
            this.ruleForm = this.detailRow;
            this.imageUrl = this.detailRow.avatar;
            this.ruleForm.isAdmin = (this.detailRow.isAdmin === '是') ? true : false;
        },

    },
    methods: {
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.imageUrl === ''){
                        this.$message.error('请上传头像！');
                    }else{
                        const paramsEdit = {
                            aid: this.ruleForm.aid,
                            name: this.ruleForm.name,
                            gender: this.ruleForm.gender === '男' ? 1 : 0,
                            phone: this.ruleForm.phone,
                            email: this.ruleForm.email,
                            address: this.ruleForm.address,
                            maritalStatus: this.ruleForm.marital_status === '已婚' ? 1 : 0,
                            avatar: this.imageUrl,
                            isAdmin: this.ruleForm.isAdmin,
                            school: this.ruleForm.school,
                        }
                        const paramsAdd = {
                            aid: this.ruleForm.aid,
                            account: this.ruleForm.account,
                            name: this.ruleForm.name,
                            gender: this.ruleForm.gender === '男' ? 1 : 0,
                            phone: this.ruleForm.phone,
                            email: this.ruleForm.email,
                            address: this.ruleForm.address,
                            maritalStatus: this.ruleForm.marital_status === '已婚' ? 1 : 0,
                            avatar: this.imageUrl,
                            isAdmin: this.ruleForm.isAdmin,
                            school: this.ruleForm.school,
                        }
                        if(this.ruleForm.aid === ''){
                            // 新增用户
                            // console.log(paramsAdd);
                            // console.log(_this.ruleForm);
                            addUser(paramsAdd).then(res=>{
                                this.$message({
                                    message: res.data.message,
                                    type: 'success',
                                });
                                setTimeout(() => {
                                    // 关闭弹窗
                                    this.visible = false;
                                }, 1000)
                            })

                        }else{
                            // 点击提交 调用接口 编辑
                            editUser(paramsEdit).then(res=>{
                                this.$message({
                                    message: res.data.message,
                                    type: 'success',
                                });
                                setTimeout(() => {
                                    // 关闭弹窗
                                this.visible = false;
                                }, 1000)
                            })
                        }
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.ruleForm.name = '';
            this.ruleForm.gender = '';
            this.ruleForm.phone = '';
            this.ruleForm.email = '';
            this.ruleForm.address = '';
            this.ruleForm.marital_status = '';
            this.ruleForm.school = '';
        },
        close(){
            //   $emit('update:show', false);
            this.$router.go(0);
        },

        // 上传图片
        uploadImage(file){
            // 定义唯一文件名
            var fileName = 'user' + `${Date.parse(new Date())}` + '.jpg';
            client().multipartUpload(fileName, file.file).then(res=>{
                this.$message.success('上传成功！');
                this.imageUrl = 'https://recruitment-files.oss-cn-chengdu.aliyuncs.com/' + fileName;
            });
        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
            const isLt5M = file.size / 1024 / 1024 < 5;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 jpg或png格式 格式!');
            }
            if (!isLt5M) {
                this.$message.error('上传头像图片大小不能超过 5MB!');
            }
            return isJPG && isLt5M;
        },

    },
}
</script>

<style scoped>
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
